package com.xsomnus.rpc.provider.registry;

import com.xsomnus.rpc.common.common.Constants;
import com.xsomnus.rpc.common.config.ZkClient;
import com.xsomnus.rpc.provider.config.RPCServerProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.zookeeper.CreateMode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;

/**
 * @author @xsomnus666_xiawenye★
 * @since 2019/4/22 0022 14:09
 * 当你发现自己的才华撑不起野心时，就请安静下来学习吧
 * 服务注册
 */
@Slf4j
@Configuration
@EnableConfigurationProperties({RPCServerProperties.class})
public class ServiceRegistry {

    @Autowired
    RPCServerProperties rpcServerProperties;

    @Autowired
    ZkClient zkClient;

    public void register(String data) {
        log.debug("zookeeper注册地址: {}", data);
        if (StringUtils.isNoneEmpty(data)) {
            addRootNode();
            createNode(data);
        }
    }

    private void createNode(String data) {
        String path = Constants.ZK_REGISTRY_PATH + Constants.PATH_DELIMETER + "provider";
        zkClient.createNode(CreateMode.EPHEMERAL_SEQUENTIAL, path, data);
    }

    private void addRootNode() {
        if (!zkClient.checkExists(Constants.ZK_REGISTRY_PATH)) {
            log.debug("创建zookeeper主节点 {}", Constants.ZK_REGISTRY_PATH);
            zkClient.createNode(CreateMode.PERSISTENT, Constants.ZK_REGISTRY_PATH);
        }
    }
}
